<?php

App::import('Sanitize');

class MessagesController extends AppController{

	var $helpers = array('Js' => array('Jquery'), 'Html', 'Form');
	var $name = 'Messages';
	var $uses = array('Message', 'User', 'Friend', 'Invite', 'RequestFriend', 'Post');
	
	function index($id = null, $reply = null) {
		if ($this->Session->read('account_type') != 'user') {
			$this->Session->setFlash('Access denied.');
			$this->redirect(array('action' => 'index'));
		}
		
	 	$this->set('user', $this->Session->read('user'));
	 	$this->set('messages', $this->Message->find('all'));	
	 	
		$this->Message->id = $id;
		$this->set('message', $this->Message->read());
		
		if ($reply == 'reply') {
			$this->set('replyIsClicked', true);
		} else {
			$this->set('replyIsClicked', false);
		}
	}
	
	
	function messages_sent($id = null) {
		if ($this->Session->read('account_type') != 'user') {
			$this->Session->setFlash('Access denied.');
			$this->redirect(array('action' => 'index'));
		}
		
		$this->set('user', $this->Session->read('user'));
		$this->Message->id = $id;
		$this->set('messages', $this->Message->find('all'));
		$this->set('message', $this->Message->read());
	}
	
	function compose() {
		if($this->Session->read('account_type') != 'user')
    		$this->redirect(array('action' => 'index'));
    	$user = $this->Session->read('user');
    	$this->set('user', $user);
    	
    	/* if the form is submitted */
    	if (!empty($this->data)):
			$emails = explode(",", $this->data['Message']['emails']);	
			foreach ($emails as $email):
			
				$user_found = $this->User->find('first', array('conditions' => array('User.email_addr' => $email)));
				
				if ($user_found) {
					$a; $b; $isFriend;
					if ($user['User']['id'] < $user_found['User']['id'] ) {
						$a = $user['User']['id'];
						$b = $user_found['User']['id'];
					} else {
						$a = $user_found['User']['id'];
						$b = $user['User']['id'];
					}

					$isFriend = $this->Friend->find('first', array('conditions'=>array('Friend.user1_id'=>$a, 'Friend.user2_id'=>$b)));
					if (empty($isFriend))
						$this->Session->setFlash('You can only send messages to your friends. ');
					else {
						$this->data['Message']['receiver_id'] = $user_found['User']['id'];
						if ($this->Message->save($this->data)) {
							$this->Session->setFlash("Message is Sent.");
							$this->redirect(array('action'=>'index'));
						}
					}
    			} else {
    				$this->Session->setFlash('Invalid Email: ' . $email);
    			}
			endforeach;
    	endif;
	}
	
	function delete($id) {
		
		if ($this->Message->delete($id)) {
			$this->Session->setFlash('The message with id: ' . $id . ' has been deleted.');
			$this->redirect(array('action' => 'index'));
		}
		
	}
	

	
	
	
	
}
